from django.conf import settings
from django.core.files.storage import Storage
from fdfs_client.client import Fdfs_client


class FastDFSStorage(Storage):
    @staticmethod
    def _save(name, content):
        """文件的保存方法"""
        # name: 上传文件的名称
        # content: 包含上传文件内容的File对象, content.read()获取上传文件内容
        client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        res = client.upload_by_buffer(content.read())
        if res.get('Status') != 'Upload successed.':
            raise Exception('上传文件到FDFS系统失败')

        file_id = res.get('Remote file_id')
        return file_id

    def exists(self, name):
        return False

    def url(self, name):
        return settings.FDFS_URL + name
